package com.supermap.wzhy.data;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.*;
import java.util.*;
import java.util.zip.ZipOutputStream;
//import java.util.zip.ZipEntry;
//import java.util.zip.ZipFile;


/**
 * Created by W.Qiong on 15-4-22.
 * 读取zip文件工具类
 */
public class ZipUtil {
    /** 默认Excel文件上传服务器路径（被解析时的路径） */
    private static String uploadFilePath = MacroFinalInfo.userHome;

    /**
     * ant读取zip文件下的所有数据
     * @param fileName
     * @throws Exception
    */
    public static Map<String,List<String[]>> readFiles(String fileName) {
        String fullpath = uploadFilePath + fileName ;
        Map<String,List<String[]>> allfiles = new HashMap<>() ;
        try {
            ZipFile zipFile = new ZipFile(fullpath,"GB18030") ;
            Enumeration<ZipEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()){
                ZipEntry entry = entries.nextElement() ;
                String name = entry.getName() ;
                String table = name;  //name.split("\\.")[0] ;
                //跳过目录 不进行下级搜索
                if(entry.isDirectory()){continue;}
                long size = entry.getSize() ;
                if(size>0){
                    List<String[]> fileData = new ArrayList<>() ;
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(zipFile.getInputStream(entry),"GBK")) ;
                    String line ="";
                    while ((line = br.readLine()) != null) {
                        String[] row= line.split(",");
                        fileData.add(row);
                    }
                    if(allfiles.containsKey(table)){
                        fileData.remove(0) ;
                        allfiles.get(table).addAll(fileData);
                    }else{
                        allfiles.put(table,fileData) ;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return allfiles;
    }


    public static List<String> getFileNames(String fileName) {
        String fullpath = uploadFilePath + fileName ;
        List<String> fileNames = new ArrayList<>();
        try {
            ZipFile zipFile = new ZipFile(fullpath,"GB18030") ;
            Enumeration<ZipEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement() ;
                String name = entry.getName() ;
                String table = name;  //name.split("\\.")[0] ;
                //跳过目录 不进行下级搜索
                if(entry.isDirectory()) {
                    continue;
                }
                fileNames.add(table);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileNames;
    }

    public static List<String[]> getFileData(String zipFileName, String fileName) {
        String fullpath = uploadFilePath + zipFileName ;
        List<String[]> fileData = new ArrayList<>();
        try {
            ZipFile zipFile = new ZipFile(fullpath,"GB18030") ;
            Enumeration<ZipEntry> entries = zipFile.getEntries();
            while (entries.hasMoreElements()){
                ZipEntry entry = entries.nextElement() ;
                String name = entry.getName() ;
                String table = name;  //name.split("\\.")[0] ;
                //跳过目录 不进行下级搜索
                if(entry.isDirectory()){continue;}
                if(!table.equals(fileName)) {
                    continue;
                }
                long size = entry.getSize() ;
                if(size > 0){
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(zipFile.getInputStream(entry),"GBK")) ;
                    String line ="";
                    while ((line = br.readLine()) != null) {
                        String[] row= line.split(",");
                        fileData.add(row);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return fileData;
    }

    public boolean createZipFile(String sourcePath ,String destPath){

        File sourceFile = new File(sourcePath) ;
        if(!sourceFile.exists()){ return  false;}
        try {
            FileInputStream inStream = new FileInputStream(sourceFile);
            BufferedInputStream bInStream = new BufferedInputStream(
                    inStream);
            ZipEntry entry = new ZipEntry(sourceFile.getName());
            OutputStream out =new FileOutputStream(new File(destPath)) ;
            ZipOutputStream outputstream = new ZipOutputStream(out) ;
            outputstream.putNextEntry(entry);

            final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
            long streamTotal = 0; // 接受流的容量
            int streamNum = 0; // 流需要分开的数量
            int leaveByte = 0; // 文件剩下的字符数
            byte[] inOutbyte; // byte数组接受文件的数据


            streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
            streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
            leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量

            if (streamNum > 0) {
                for (int j = 0; j < streamNum; ++j) {
                    inOutbyte = new byte[MAX_BYTE];
                    // 读入流,保存在byte数组
                    bInStream.read(inOutbyte, 0, MAX_BYTE);
                    outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
                }
            }
            // 写出剩下的流数据
            inOutbyte = new byte[leaveByte];
            bInStream.read(inOutbyte, 0, leaveByte);
            outputstream.write(inOutbyte);
            outputstream.closeEntry(); // Closes the current ZIP entry
            bInStream.close(); // 关闭
            inStream.close();
            return  true ;
        }catch ( Exception e){
              System.out.println("生成zip错误！");
        }
        return  false ;
    }
    /**
     * java.util.zip包读取 存在编码问题 只能用jdk1.6 暂保留废弃不用
     *
     * @throws Exception
     */
//    public static void readFiles(String filepath) throws Exception{
//        ZipFile zf = new ZipFile(filepath) ;
//        ZipInputStream zip = new ZipInputStream(new FileInputStream(filepath));
//        Map<String,List> allfiles = new HashMap<>() ;
//        ZipEntry entry =null ;
//        try {
//            while ((entry = zip.getNextEntry()) != null){
//                long size = entry.getSize();
//                String name = entry.getName();
//                int rownum =0 ;
////            if(size>0){
//                MessagePrintUtil.printMsg(name);
//                BufferedReader br = new BufferedReader(new InputStreamReader(zf.getInputStream(entry))) ;
//                String line;
//                while ((line = br.readLine()) != null) {
//                    rownum++;
////                    System.out.println(line);
//                }
////            }
//                System.out.println(name+":"+rownum);
//            }
//        }catch (Exception e){
//            e.printStackTrace();
//        }

//    }

    public static void  main(String[] args){
        String path = "C:\\Users\\W.Qiong\\Desktop\\2014年2月.zip";
        try {
            MessagePrintUtil.printMsg("开始："+new Date().toString());
            ZipUtil.readFiles(path);
            MessagePrintUtil.printMsg("结束：" + new Date().toString());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
